package com.lz.sports.dialog

import android.os.Bundle
import android.view.View
import androidx.lifecycle.lifecycleScope
import com.lz.library.dialog.BaseDialogFragment
import com.lz.library.extension.click
import com.lz.library.extension.showToast
import com.lz.sports.R
import com.lz.sports.databinding.DialogTestInsertBinding
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

class TestInsertDialog : BaseDialogFragment<DialogTestInsertBinding>() {

    companion object {
        fun newInstance(position: Int): TestInsertDialog = TestInsertDialog().apply {
            arguments = Bundle().also { it.putInt("position", position) }
        }
    }

    override fun getLayoutRes(): Int = R.layout.dialog_test_insert

    override fun initData(v: View, savedState: Bundle?) {
        lifecycleScope.launch {
            arrayOf(binding.tvConfirm, binding.tvCancel).click().collect {
                when (it.id) {
                    R.id.tv_cancel -> dismiss()
                    R.id.tv_confirm -> {
                        if (context is OnConfirmListener) {
                            confirm()
                        }
                    }
                }
            }
        }
    }

    private fun confirm() {
        val position = arguments!!.getInt("position", 0)
        val mac = binding.etTest.text.toString().trim().uppercase()
        if (mac.length < 12 || mac.length.and(1) == 1) {
            "请输入正确的mac地址".showToast()
            return
        }
        val number = binding.etTest2.text.toString().trim().toIntOrNull()
        if (number == null) {
            "请输入正确的编号".showToast()
            return
        }
        (context as OnConfirmListener).onConfirm(this@TestInsertDialog, mac, number, position)
    }

    interface OnConfirmListener {

        fun onConfirm(dialog: TestInsertDialog, mac: String, num: Int, position: Int)
    }
}